let express = require('express');
let router = express.Router();
var multer = require('../../components/multerUtil');
let filter = require('../../components/filter');
let xlsx = require('node-xlsx');

/**
 * 查询试题数据 by p 2018-06-11
 *
 * 按条件查询试题数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;

    var limits = "";
    var sql = "";
    var datas = [];

    if (params.subjectId !== undefined && params.subjectId !== "") {
        sql = "subjectId = ?";
        datas.push(params.subjectId);
    }

    if (params.types === 0 && params.types === 1) {
        sql += (sql === "" ? "" : " and ") + "types = ?";
        datas.push(params.types);
    }


    req.app.db.query("select count(1) as totalCount from question" + (sql === "" ? "" : " where ") + sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from question" + (sql === "" ? "" : " where ") + sql + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "data": results, "totalCount": totalCount});
        });
    });


});

/**
 * 查看试题数据 by p 2018-06-11
 *
 * 按id查看指定的试题信息
 */
router.get('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query("select * from question where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});

/**
 * 保存试题数据 by p 2018-06-11
 *
 * 支持新增、修改
 * id 大于 0时，修改
 * 其他情况 新增
 */
function saveQuestion(params, req, res) {
    var sql = "";
    var datas = [];
    var types = 0;
    var optionA = "";
    var optionB = "";
    var optionC = "";
    var optionD = "";
    var optionE = "";
    var optionF = "";
    var optionG = "";
    var optionNum = 0;

    if (params.subjectId === undefined && params.subjectId === "") {
        res.json({"success": false, "message": "父类编码不正确！"});
        return;
    }

    if (params.types !== undefined) {
        types = params.types;
    }

    if (params.title === undefined && params.title === "") {
        res.json({"success": false, "message": "问题不能为空！"});
        return;
    }

    if (params.optionA !== undefined && params.optionA !== "") {
        optionA = params.optionA;
        optionNum++;
    }

    if (params.optionB !== undefined && params.optionB !== "") {
        optionB = params.optionB;
        optionNum++;
    }

    if (params.optionC !== undefined && params.optionC !== "") {
        optionC = params.optionC;
        optionNum++;
    }

    if (params.optionD !== undefined && params.optionD !== "") {
        optionD = params.optionD;
        optionNum++;
    }

    if (params.optionE !== undefined && params.optionE !== "") {
        optionE = params.optionE;
        optionNum++;
    }

    if (params.optionF !== undefined && params.optionF !== "") {
        optionF = params.optionF;
        optionNum++;
    }

    if (params.optionG !== undefined && params.optionG !== "") {
        optionG = params.optionG;
        optionNum++;
    }

    if (optionNum < 4) {
        res.json({"success": false, "message": "最少需要4个选项！"});
        return;
    }

    if (params.keys === undefined && params.keys === "") {
        res.json({"success": false, "message": "答案不能为空！"});
        return;
    }

    datas.push(params.subjectId);
    datas.push(types);
    datas.push(params.title);
    datas.push(optionA);
    datas.push(optionB);
    datas.push(optionC);
    datas.push(optionD);
    datas.push(optionE);
    datas.push(optionF);
    datas.push(optionG);
    datas.push(params.keys);

    if (params.id > 0) {
        sql = "update question set subjectId = ?, types = ?, title = ? , optionA = ?, optionB = ?, optionC = ?, optionD = ?, optionE = ?, optionF = ?, optionG = ?, `keys` = ? where id = ?";
        datas.push(params.id);
    } else {
        sql = "insert into question(subjectId, types, title, optionA, optionB, optionC, optionD, optionE, optionF, optionG, `keys`) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    }

    req.app.db.query(sql, datas, function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }
        res.json({"success": true, "message": ""});
    });
}

router.put('/:id', function (req, res, next) {
    saveQuestion(req.body, req, res);
});

router.post('/', function (req, res, next) {
    saveQuestion(req.body, req, res);
});

/**
 * 删除试题信息 by v 2018-06-11
 *
 * 按id删除指定的试题信息
 */
router.delete('/:id', function (req, res, next) {
    let params = req.params;

    req.app.db.query('delete from question where id = ?', [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.deleteMsg});
    });
});

/**
 * 倒入试题
 *
 */
router.post('/import', multer.single("uploadFile"), function (req, res, next) {
    if (req.file !== undefined) {
        let fileFormat = (req.file.originalname).split(".");
        let fileName = global.dirname + "/" + req.file.path;// + "." + fileFormat[fileFormat.length - 1];
        var sheets = xlsx.parse(fileName);
        var datas = [];

        if (sheets.length > 0) {
            for (var rowId in sheets[0]['data']) {
                var optionNum = 0;
                var row = sheets[0]['data'][rowId];

                if (row[0] === undefined || row[0] === "") {
                    res.json({"success": false, "message": "第" + (Number(rowId) + 1) + "行，父类编码不正确！"});
                    return;
                }

                if (row[1] === undefined) {
                    row[1] = 0
                }

                if (row[2]  === undefined || row[2] === "") {
                    res.json({"success": false, "message": "第" + (Number(rowId) + 1) + "行，问题不能为空！"});
                    return;
                }

                if (row[3] !== undefined && row[3] !== "") {
                    optionNum++;
                }

                if (row[4] !== undefined && row[4] !== "") {
                    optionNum++;
                }

                if (row[5] !== undefined && row[5] !== "") {
                    optionNum++;
                }

                if (row[6] !== undefined && row[6] !== "") {
                    optionNum++;
                }

                if (row[7] !== undefined && row[7] !== "") {
                    optionNum++;
                }

                if (row[8] !== undefined && row[8] !== "") {
                    optionNum++;
                }

                if (row[9] !== undefined && row[9] !== "") {
                    optionNum++;
                }

                if (optionNum < 4) {
                    res.json({"success": false, "message": "第" + (Number(rowId) + 1) + "行，最少需要4个选项！"});
                    return;
                }

                if (row[10] === undefined || row[10] === "") {
                    res.json({"success": false, "message": "第" + (Number(rowId) + 1) + "行，答案不能为空！"});
                    return;
                }

                datas.push(row);
            }

            for (var i = 0; i < datas.length; i ++) {
                var sql = "insert into question(subjectId, types, title, optionA, optionB, optionC, optionD, optionE, optionF, optionG, `keys`) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

                req.app.db.query(sql, datas[i], function (err, results) {
                    if (err) {
                        res.json({"success": false, "message": global.databaseErr, "detail": err});
                        return;
                    }
                });
            }

            res.json({"success": false, "message": "共计" + datas.length + "条数据导入成功！"});
            return;
        }

        res.json({"success": false, "message": "导入文件格式不正确！"});
        return;
    }

    res.json({"success": false, "message": "没有导入文件！"});
    return;
});

function testData(params) {
    var datas = [];
    var types = 0;
    var optionA = "";
    var optionB = "";
    var optionC = "";
    var optionD = "";
    var optionE = "";
    var optionF = "";
    var optionG = "";
    var optionNum = 0;

    if (params.subjectId === undefined && params.subjectId === "") {
        res.json({"success": false, "message": "父类编码不正确！"});
        return;
    }

    if (params.types !== undefined) {
        types = params.types;
    }

    if (params.title === undefined && params.title === "") {
        res.json({"success": false, "message": "问题不能为空！"});
        return;
    }

    if (params.optionA !== undefined && params.optionA !== "") {
        optionA = params.optionA;
        optionNum++;
    }

    if (params.optionB !== undefined && params.optionB !== "") {
        optionB = params.optionB;
        optionNum++;
    }

    if (params.optionC !== undefined && params.optionC !== "") {
        optionC = params.optionC;
        optionNum++;
    }

    if (params.optionD !== undefined && params.optionD !== "") {
        optionD = params.optionD;
        optionNum++;
    }

    if (params.optionE !== undefined && params.optionE !== "") {
        optionE = params.optionE;
        optionNum++;
    }

    if (params.optionF !== undefined && params.optionF !== "") {
        optionF = params.optionF;
        optionNum++;
    }

    if (params.optionG !== undefined && params.optionG !== "") {
        optionG = params.optionG;
        optionNum++;
    }

    if (optionNum < 4) {
        res.json({"success": false, "message": "最少需要4个选项！"});
        return;
    }

    if (params.keys === undefined && params.keys === "") {
        res.json({"success": false, "message": "答案不能为空！"});
        return;
    }

    datas.push(params.subjectId);
    datas.push(types);
    datas.push(params.title);
    datas.push(optionA);
    datas.push(optionB);
    datas.push(optionC);
    datas.push(optionD);
    datas.push(optionE);
    datas.push(optionF);
    datas.push(optionG);
    datas.push(params.keys);
}
module.exports = router;
